package com.jf.docsify.common.utils;

import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;

/**
 * Description: 接口返回
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/8/2.1       chenwr    2022/8/2           Create
 * </pre>
 * @date 2022/8/2
 */
public class Resp extends Kv {
    public static final int SUCCESS = 0;
    public static final String MSG_SUCCESS = "成功";
    public static final int ERROR = -1;
    public static final String MSG_ERROR = "失败";


    private Resp() {
    }

    public static Resp resp(boolean success) {
        return success ? success() : error();
    }

    public static Resp resp(boolean success, Object data) {
        return success ? success(data) : error();
    }

    public static Resp error(String msg) {
        return error(ERROR, msg);
    }

    public static Resp error(int code) {
        return error(code, MSG_ERROR);
    }

    public static Resp error() {
        return error(ERROR, MSG_ERROR);
    }

    public static Resp error(int code, String msg) {
        Resp resp = new Resp();
        resp.code(code);
        if (msg != null) {
            resp.msg(msg);
        }
        return resp;
    }

    public static Resp success() {
        return success(null);
    }

    public static Resp success(Object data) {
        Resp resp = new Resp().code(SUCCESS).msg(MSG_SUCCESS).success(true);
        if (data != null) {
            resp.data(data);
        }
        return resp;
    }

    public Integer getCode() {
        return getInt("code");
    }

    public Resp success(boolean success) {
        set("success", success);
        return this;
    }

    public Boolean getSuccess() {
        return getBoolean("success");
    }

    public Resp code(int code) {
        set("code", code);
        return this;
    }

    public <T> T getData() {
        return getAs("data");
    }

    public Resp data(Object data) {
        set("data", data);
        return this;
    }

    public String getMsg() {
        return getStr("msg");
    }

    public Resp msg(String msg) {
        set("msg", msg);
        return this;
    }

    public <T extends Controller> void done(T controller) {
        controller.renderJson(this);
    }
}